﻿#include "QtWidgetsApplication.h"

QtWidgetsApplication::QtWidgetsApplication(QWidget *parent)
    : QMainWindow(parent)
{
    // 创建登录窗口 并显示
    loginWindow = new Login();
    loginWindow->show();
    ConnectInit();      // 登录窗口信号槽

    // 注册窗口默认不创建
    regWindow = nullptr;
    regFlag = false;

    // 菜单窗口
    m_pMenuWindow = new menu;

    m_pBookTicketWindow     = nullptr;
    m_pqueryTicket          = nullptr;

    m_pBookHotelWindow      = nullptr;
    m_pqueryHotel           = nullptr;

    m_pBookTaxiWindow       = nullptr;
    m_pqueryTaxi            = nullptr;

    m_pPeekOrderWindow      = nullptr;
    m_pqueryOrder           = nullptr;
    m_pdelBuf               = nullptr;

    m_pPeekRoadWindow       = nullptr;
    m_pqueryRoad            = nullptr;
   
    // 数据库连接
    db = new connection();
}

QtWidgetsApplication::~QtWidgetsApplication()
{
    delete loginWindow;
    if (regFlag) {
        delete regWindow;
    }
    delete db;
    delete m_pMenuWindow;
}

/*-------------------------------------------------------登录窗口----------------------------------------------*/
// 退出按钮处理逻辑
void QtWidgetsApplication::OnBackBtn()
{
    loginWindow->close();
    this->close();
}

// 注册按钮的响应函数
void QtWidgetsApplication::OnRegBtn()
{
    // 产生注册窗口
    regWindow = new Registe();
    regFlag = true;

    // 关闭登录窗口
    loginWindow->close();

    // 显示注册窗口
    regWindow->show();

    // 设置注册窗口的信号槽连接
    RegWindowConnectInit();
}

// 登录按钮响应函数
void QtWidgetsApplication::OnLoginBtn() 
{
    QSqlQuery query(db->GetDatabase());
    QString str = QString("select userpassword from customer where userid = '%1'\
                           ").arg(loginWindow->login.lineEdit_uerid->text());
    query.exec(str);
    if (!query.next()) {            // 没找到该用户
        QMessageBox::warning(this, QString("User Not Found"), QString("Can't find User %1").arg(loginWindow->login.lineEdit_uerid->text()), QMessageBox::Ok);
        return;
    }

    
    // 找到用户后进行取值
    user_id = loginWindow->login.lineEdit_uerid->text();
    QString user_password = loginWindow->login.lineEdit_userpassword->text();
    if (user_password != query.value(0).toString()) {    // 输入密码错误
        QMessageBox::warning(this, QString("Password error"), QString("Wrong password!"), QMessageBox::Ok);
    }

    
/*进入管理界面*/
    // 关闭登录页面
    loginWindow->close();

    // 打开管理页面
    m_pMenuWindow->ui.label_userid->setText(user_id);
    m_pMenuWindow->show();

    // 设置管理窗口信号槽
    MenuWindowConnectInit();

}

// 登录窗口信号槽
void QtWidgetsApplication::ConnectInit()
{
    connect(loginWindow->login.registe, &QPushButton::clicked, this, &QtWidgetsApplication::OnRegBtn);
    connect(loginWindow->login.back, &QPushButton::clicked, this, &QtWidgetsApplication::OnBackBtn);
    connect(loginWindow->login.login, &QPushButton::clicked, this, &QtWidgetsApplication::OnLoginBtn);
}


/*--------------------------------------------------------------注册窗口---------------------------------------------------*/
// 注册按钮响应函数
void QtWidgetsApplication::OnRegwindowRegBtn()
{
    QSqlQuery query(db->GetDatabase());
    QString str = QString("insert into customer values(null,'%1','%2','%3','%4','%5')")
        .arg(regWindow->reg.lineEdit_name->text())                      // 名字
        .arg(regWindow->reg.lineEdit_phone->text())                     // 电话
        .arg(regWindow->reg.lineEdit_sex->text())                       // 性别
        .arg(regWindow->reg.lineEdit_userid->text())                    // 用户名
        .arg(regWindow->reg.lineEdit_userpassword->text());             // 密码
    if (!query.exec(str)) {
        QMessageBox::warning(this, QString("failed"), QString("failed!, user another user-id to retry"), QMessageBox::Ok);
        return;         // 注册失败，直接返回
    }
    // 1、注册成功，不需要登录，直接进入系统    2、注册成功，返回登录  
    loginWindow->login.lineEdit_uerid->setText(regWindow->reg.lineEdit_userid->text());
    loginWindow->show();
    regWindow->close();
}

// 返回按钮响应函数
void QtWidgetsApplication::OnRegwindowBackBtn()
{
    regWindow->close();
    loginWindow->show();
}

// 返回窗口信号槽
void QtWidgetsApplication::RegWindowConnectInit()
{
    connect(regWindow->reg.btn_reg, &QPushButton::clicked, this, &QtWidgetsApplication::OnRegwindowRegBtn);
    connect(regWindow->reg.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnRegwindowBackBtn);
}


/*--------------------------------------------------------------主菜单窗口---------------------------------------------------*/
// 退出按钮响应函数
void QtWidgetsApplication::OnMenuWindowBackBtn()
{
    m_pMenuWindow->close();
}

// 订机票按钮响应函数
void QtWidgetsApplication::OnMenuWindowBookTicketBtn()
{
    // 关闭菜单窗口
    m_pMenuWindow->close();

    // 创建订票窗口
    m_pBookTicketWindow = new Ticket();

    // 查询票务信息
    m_pqueryTicket = new QSqlQuery(db->GetDatabase());
    QString str = QString("select * from flight");
    if (!m_pqueryTicket->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init ticket infomation, database flight 'select' error!"),QMessageBox::Ok );
    }

    // 票务信息设置到窗口
    AddTicketToBookTicketWindow();

    // 显示订票窗口
    m_pBookTicketWindow->show();

    // 绑定定标窗口信号槽
    BookTicketWindowConnectInit();
}

// 订旅馆按钮响应函数
void QtWidgetsApplication::OnMenuWindowBookHotelBtn()
{
    // 关闭菜单窗口
    m_pMenuWindow->close();

    // 创建订旅馆窗口
    m_pBookHotelWindow = new Hotel();

    // 查询房间信息
    m_pqueryHotel = new QSqlQuery(db->GetDatabase());
    QString str = QString("select * from hotel");
    if (!m_pqueryHotel->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init hotel infomation, database hotel 'select' error!"), QMessageBox::Ok);
    }

    // 房间信息设置到窗口
    AddRoomsToBookHotelWindow();

    // 显示订旅馆窗口
    m_pBookHotelWindow->show();

    // 绑定窗口信号槽
    BookHotelWindowConnectInit();
}

// 订出租车按钮响应函数
void QtWidgetsApplication::OnMenuWindowBookTaxiBtn()
{
    // 关闭菜单窗口
    m_pMenuWindow->close();

    // 创建订出租车窗口
    m_pBookTaxiWindow = new Taxi();

    // 查询出租车信息
    m_pqueryTaxi = new QSqlQuery(db->GetDatabase());
    QString str = QString("select * from car");
    if (!m_pqueryTaxi->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init car infomation, database car 'select' error!"), QMessageBox::Ok);
    }

    // 出租车信息设置到窗口
    AddCarsToBookCarWindow();

    // 显示订出租车窗口
    m_pBookTaxiWindow->show();

    // 绑定窗口信号槽
    BookCarWindowConnectInit();
}

// 个人订单按钮响应函数
void QtWidgetsApplication::OnMenuWindowOrderBtn()
{
    // 关闭菜单窗口
    m_pMenuWindow->close();

    // 创建查询订单窗口
    m_pPeekOrderWindow = new Order();

    // 创建执行查询时需要的QSqlQuery 实体
    m_pqueryOrder = new QSqlQuery(db->GetDatabase());

    // 查询并设置查询到的订单信息到窗口控件
    AddOrderToPeekOrderWindow();

    // 显示订出租车窗口
    m_pPeekOrderWindow->show();

    // 绑定窗口信号槽
    PeekOrderWindowConnectInit();
}

// 路线按钮响应函数
void QtWidgetsApplication::OnMenuWindowRoadBtn()
{
    // 关闭菜单窗口
    m_pMenuWindow->close();

    // 创建查询路线窗口
    m_pPeekRoadWindow = new Road();

    // 创建执行查询时需要的QSqlQuery 实体
    m_pqueryRoad = new QSqlQuery(db->GetDatabase());

    // 查询并设置查询到的路线信息到窗口控件
    AddRoadToPeekRoadWindow();

    // 显示路线窗口
    m_pPeekRoadWindow->show();

    // 绑定窗口信号槽
    PeekRoadWindowConnectInit();
}

// 管理数据库按钮响应函数
void QtWidgetsApplication::OnMenuWindowManageBtn()
{

}

// 信号槽
void QtWidgetsApplication::MenuWindowConnectInit()
{
    connect(m_pMenuWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowBackBtn);
    connect(m_pMenuWindow->ui.btn_BookHotel, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowBookHotelBtn);
    connect(m_pMenuWindow->ui.btn_BookTaxi, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowBookTaxiBtn);
    connect(m_pMenuWindow->ui.btn_BookTicket, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowBookTicketBtn);
    connect(m_pMenuWindow->ui.btn_myOrder, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowOrderBtn);
    connect(m_pMenuWindow->ui.btn_travelRoad, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowRoadBtn);
//    connect(m_pMenuWindow->ui.btn_manage, &QPushButton::clicked, this, &QtWidgetsApplication::OnMenuWindowManageBtn);
}


/*--------------------------------------------------------------订飞机票窗口---------------------------------------------------*/

//  退出按钮响应函数
void QtWidgetsApplication::OnBookTicketWindowBackBtn()
{
    // 关闭订票窗口
    m_pBookTicketWindow->close();
    
    // 清除订票窗口
    delete m_pBookTicketWindow;
    m_pBookTicketWindow = nullptr;

    // 清除过时的查询的票务信息
    delete m_pqueryTicket;
    m_pqueryTicket = nullptr;

    // 显示菜单窗口
    m_pMenuWindow->show();
}

//  选择按钮响应函数
void QtWidgetsApplication::OnBookTicketWindowSelectBtn()
{
    QString selected = m_pBookTicketWindow->ui.comBox->currentText();
    // 判断座位是否足够
    QString str = QString("select leftSeats from flight where noFlight = %1").arg(selected);
    if (!m_pqueryTicket->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find leftSeats infomation, database flight 'select' error!"), QMessageBox::Ok);
    }
    m_pqueryTicket->next();
    int leftSeats = m_pqueryTicket->value(0).toInt();
    if (leftSeats == 0) {               // 座位不够
        QMessageBox::warning(this, QString("error!"), QString("There are not enough seats!"), QMessageBox::Ok);
        return;
    }

    // 更新座位
    leftSeats--;
    QString str1 = QString("update flight set leftSeats = %1 where noFlight = %2").arg(leftSeats).arg(selected);
    QString str2 = QString("insert into customerflight values('%1',%2,'%3','%4')").arg(user_id).arg(selected).arg(QDate::currentDate().toString(QString("yyyy.MM.dd"))).arg(QTime::currentTime().toString());
    
   
    QSqlDatabase::database().transaction();     // 开启一个事务
    bool update_flag = m_pqueryTicket->exec(str1);
    bool insert_flag = m_pqueryTicket->exec(str2);
    if (!update_flag || !insert_flag) {    // 只要有一个没有执行成功
//        QSqlDatabase::database().rollback();    // 回滚             
        QMessageBox::warning(this, QString("error!"), QString("Buy ticket failed, there are some error in system database!"), QMessageBox::Ok);
        return;
    }
    QSqlDatabase::database().commit();          // 提交

    // 重新查询票务信息，更新前端显示
    m_pqueryTicket = new QSqlQuery(db->GetDatabase());
    QString str3 = QString("select * from flight");
    if (!m_pqueryTicket->exec(str3)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init ticket infomation, database flight 'select' error!"), QMessageBox::Ok);
        if (update_flag || insert_flag) {
            QSqlDatabase::database().rollback();
        }
        return;
    }
    // 票务信息设置到窗口
    AddTicketToBookTicketWindow();
    QMessageBox::warning(this, QString("OK!"), QString("Buy sucessful!"), QMessageBox::Ok);
}

// 信号槽
void QtWidgetsApplication::BookTicketWindowConnectInit()
{
    connect(m_pBookTicketWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookTicketWindowBackBtn);
    connect(m_pBookTicketWindow->ui.btn_select, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookTicketWindowSelectBtn);
}

// 将票务信息添加到窗口
void QtWidgetsApplication::AddTicketToBookTicketWindow()
{
    QTableWidget* tmp = m_pBookTicketWindow->ui.tableWidget;
    QTableWidgetItem* item = nullptr;       // 向表格添加元素使用

    // 取出数据库中找到的元素
    std::vector<std::vector<QString>> elem_pool;
    while (m_pqueryTicket->next()) {
        std::vector<QString> buff;
        for (int i = 0; i < 7; i++) {
            buff.push_back(m_pqueryTicket->value(i).toString());
        }
        elem_pool.push_back(buff);
    }

    tmp->setRowCount(elem_pool.size());                         // 设置表格的行数
    tmp->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 设置表格不可编辑

    // 填充的顺序，因为数据库选出来的数据跟表格顺序也许不同
                           /* 编号  起飞城市  起飞日期  到达城市  到达日期  机票价格  剩余票数*/
    std::vector<int> index = { 0  ,    3   ,    5    ,   4    ,   6    ,    1     ,  2     };

    int col = 0;    // 列
    int row = 0;    // 行
    while (row < elem_pool.size()) {        // 将查到的每条信息放入表格中
        col = 0;
        while (col < 7) {
            item = new QTableWidgetItem(elem_pool[row][index[col]]);
            tmp->setItem(row, col++, item);
        }
        row++;
    }

    // 设置购买选择框
    m_pBookTicketWindow->ui.comBox->clear();
    for (int i = 0; i < elem_pool.size(); ++i) {
        m_pBookTicketWindow->ui.comBox->addItem(elem_pool[i][0]);
    }
}


/*--------------------------------------------------------------订旅馆窗口---------------------------------------------------*/

//  退出按钮响应函数
void QtWidgetsApplication::OnBookHotelWindowBackBtn()
{
    // 关闭订票窗口
    m_pBookHotelWindow->close();

    // 清除订票窗口
    delete m_pBookHotelWindow;
    m_pBookHotelWindow = nullptr;

    // 清除过时的查询的票务信息
    delete m_pqueryHotel;
    m_pqueryHotel = nullptr;

    // 显示菜单窗口
    m_pMenuWindow->show();
}

//  选择按钮响应函数
void QtWidgetsApplication::OnBookHotelWindowSelectBtn()
{
    QString selected = m_pBookHotelWindow->ui.comBox->currentText();
    // 判断房间数是否足够
    QString str = QString("select leftRooms from hotel where noHotel = %1").arg(selected);
    if (!m_pqueryHotel->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find leftRooms infomation, database hotel 'select' error!"), QMessageBox::Ok);
    }
    m_pqueryHotel->next();
    int leftRooms = m_pqueryHotel->value(0).toInt();
    if (leftRooms == 0) {               // 房间数不够
        QMessageBox::warning(this, QString("error!"), QString("There are not enough rooms!"), QMessageBox::Ok);
        return;
    }

    // 更新房间数
    leftRooms--;
    QString str1 = QString("update hotel set leftRooms = %1 where noHotel = %2").arg(leftRooms).arg(selected);
    QString str2 = QString("insert into customerhotel values('%1',%2,'%3','%4')").arg(user_id).arg(selected).arg(QDate::currentDate().toString(QString("yyyy.MM.dd"))).arg(QTime::currentTime().toString());


    QSqlDatabase::database().transaction();     // 开启一个事务
    bool update_flag = m_pqueryHotel->exec(str1);
    bool insert_flag = m_pqueryHotel->exec(str2);
    if (!update_flag || !insert_flag) {    // 只要有一个没有执行成功          
        QMessageBox::warning(this, QString("error!"), QString("Buy hotel failed, there are some error in system database!"), QMessageBox::Ok);
        if (update_flag || insert_flag) {
            QSqlDatabase::database().rollback();
        }
        return;
    }
    QSqlDatabase::database().commit();          // 提交

    // 重新查询房间数信息，更新前端显示
    m_pqueryHotel = new QSqlQuery(db->GetDatabase());
    QString str3 = QString("select * from hotel");
    if (!m_pqueryHotel->exec(str3)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init hotel infomation, database hotel 'select' error!"), QMessageBox::Ok);
        return;
    }
    // 房间数信息设置到窗口
    AddRoomsToBookHotelWindow();
    QMessageBox::warning(this, QString("OK!"), QString("Buy sucessful!"), QMessageBox::Ok);
}

// 信号槽
void QtWidgetsApplication::BookHotelWindowConnectInit()
{
    connect(m_pBookHotelWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookHotelWindowBackBtn);
    connect(m_pBookHotelWindow->ui.btn_select, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookHotelWindowSelectBtn);
}

// 将房间数信息添加到窗口
void QtWidgetsApplication::AddRoomsToBookHotelWindow()
{
    QTableWidget* tmp = m_pBookHotelWindow->ui.tableWidget;
    QTableWidgetItem* item = nullptr;       // 向表格添加元素使用

    // 取出数据库中找到的元素
    std::vector<std::vector<QString>> elem_pool;
    while (m_pqueryHotel->next()) {
        std::vector<QString> buff;
        for (int i = 0; i < 5; i++) {
            buff.push_back(m_pqueryHotel->value(i).toString());
        }
        elem_pool.push_back(buff);
    }

    tmp->setRowCount(elem_pool.size());                         // 设置表格的行数
    tmp->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 设置表格不可编辑

    // 填充的顺序，因为数据库选出来的数据跟表格顺序也许不同
                           /* 编号  宾馆  价格  剩余房间  位置*/
    std::vector<int> index = { 0  ,  1  ,  2  ,   4  ,   3   };

    int col = 0;    // 列
    int row = 0;    // 行
    while (row < elem_pool.size()) {        // 将查到的每条信息放入表格中
        col = 0;
        while (col < 5) {
            item = new QTableWidgetItem(elem_pool[row][index[col]]);
            tmp->setItem(row, col++, item);
        }
        row++;
    }

    // 设置购买选择框
    m_pBookHotelWindow->ui.comBox->clear();
    for (int i = 0; i < elem_pool.size(); ++i) {
        m_pBookHotelWindow->ui.comBox->addItem(elem_pool[i][0]);
    }
}
    

/*--------------------------------------------------------------订车窗口---------------------------------------------------*/

//  退出按钮响应函数
void QtWidgetsApplication::OnBookCarWindowBackBtn()
{
    // 关闭订车窗口
    m_pBookTaxiWindow->close();

    // 清除订车窗口
    delete m_pBookTaxiWindow;
    m_pBookTaxiWindow = nullptr;

    // 清除过时的查询的车辆信息
    delete m_pqueryTaxi;
    m_pqueryTaxi = nullptr;

    // 显示菜单窗口
    m_pMenuWindow->show();
}

//  选择按钮响应函数
void QtWidgetsApplication::OnBookCarWindowSelectBtn()
{
    QString selected = m_pBookTaxiWindow->ui.comBox->currentText();
    // 判断车辆数是否足够
    QString str = QString("select leftCars from car where noCar = %1").arg(selected);
    if (!m_pqueryTaxi->exec(str)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find leftCars infomation, database car 'select' error!"), QMessageBox::Ok);
    }
    m_pqueryTaxi->next();
    int leftCars = m_pqueryTaxi->value(0).toInt();
    if (leftCars == 0) {               // 房间数不够
        QMessageBox::warning(this, QString("error!"), QString("There are not enough cars!"), QMessageBox::Ok);
        return;
    }

    // 更新房间数
    leftCars--;
    QString str1 = QString("update car set leftCars = %1 where noCar = %2").arg(leftCars).arg(selected);
    QString str2 = QString("insert into customercar values('%1',%2,'%3','%4')").arg(user_id).arg(selected).arg(QDate::currentDate().toString(QString("yyyy.MM.dd"))).arg(QTime::currentTime().toString());


    QSqlDatabase::database().transaction();     // 开启一个事务
    bool update_flag = m_pqueryTaxi->exec(str1);
    bool insert_flag = m_pqueryTaxi->exec(str2);
    if (!update_flag || !insert_flag) {    // 只要有一个没有执行成功          
        QMessageBox::warning(this, QString("error!"), QString("Buy car failed, there are some error in system database!"), QMessageBox::Ok);
        if (update_flag || insert_flag) {
            QSqlDatabase::database().rollback();
        }
        return;
    }
    QSqlDatabase::database().commit();          // 提交

    // 重新查询房间数信息，更新前端显示
    m_pqueryTaxi = new QSqlQuery(db->GetDatabase());
    QString str3 = QString("select * from car");
    if (!m_pqueryTaxi->exec(str3)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't init car infomation, database car 'select' error!"), QMessageBox::Ok);
        return;
    }
    // 房间数信息设置到窗口
    AddCarsToBookCarWindow();
    QMessageBox::warning(this, QString("OK!"), QString("Buy sucessful!"), QMessageBox::Ok);
}

// 信号槽
void QtWidgetsApplication::BookCarWindowConnectInit()
{
    connect(m_pBookTaxiWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookCarWindowBackBtn);
    connect(m_pBookTaxiWindow->ui.btn_select, &QPushButton::clicked, this, &QtWidgetsApplication::OnBookCarWindowSelectBtn);
}

// 将车辆信息添加到窗口
void QtWidgetsApplication::AddCarsToBookCarWindow()
{
    QTableWidget* tmp = m_pBookTaxiWindow->ui.tableWidget;
    QTableWidgetItem* item = nullptr;       // 向表格添加元素使用

    // 取出数据库中找到的元素
    std::vector<std::vector<QString>> elem_pool;
    while (m_pqueryTaxi->next()) {
        std::vector<QString> buff;
        for (int i = 0; i < 5; i++) {
            buff.push_back(m_pqueryTaxi->value(i).toString());
        }
        elem_pool.push_back(buff);
    }

    tmp->setRowCount(elem_pool.size());                         // 设置表格的行数
    tmp->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 设置表格不可编辑

    // 填充的顺序，因为数据库选出来的数据跟表格顺序也许不同
                           /* 编号  车类型  价格  剩余车辆  联系电话*/
    std::vector<int> index = { 4  ,  0   ,  1  ,   2  ,     3 };

    int col = 0;    // 列
    int row = 0;    // 行
    while (row < elem_pool.size()) {        // 将查到的每条信息放入表格中
        col = 0;
        while (col < 5) {
            item = new QTableWidgetItem(elem_pool[row][index[col]]);
            tmp->setItem(row, col++, item);
        }
        row++;
    }

    // 设置购买选择框
    m_pBookTaxiWindow->ui.comBox->clear();
    for (int i = 0; i < elem_pool.size(); ++i) {
        m_pBookTaxiWindow->ui.comBox->addItem(elem_pool[i][4]);
    }
}


/*--------------------------------------------------------------查询订单窗口---------------------------------------------------*/

// 退出按钮响应函数
void QtWidgetsApplication::OnPeekOrderWindowBackBtn()
{
    // 关闭查询订单窗口
    m_pPeekOrderWindow->close();

    // 清除查询订单窗口
    delete m_pPeekOrderWindow;
    m_pPeekOrderWindow = nullptr;

    // 清除过时的查询订单信息
    delete m_pqueryOrder;
    m_pqueryOrder = nullptr;

    // 清除映射表
    delete m_pdelBuf;
    m_pdelBuf = nullptr;

    // 显示菜单窗口
    m_pMenuWindow->show();
}

// 删除按钮响应函数
void QtWidgetsApplication::OnPeekOrderWindowDeleteBtn()
{
    if (m_pdelBuf->size() == 0) {
        QMessageBox::warning(this, QString("提示"), QString("您没有任何订单！"), QMessageBox::Ok);
        return;
    }
    int index = m_pPeekOrderWindow->ui.comboBox->currentText().toInt() - 1;
    QString tableName1 = (*m_pdelBuf)[index][0];
    QString tableKey11 = (*m_pdelBuf)[index][1];
    QString tableKey12 = (*m_pdelBuf)[index][2];
    QString tableval11 = (*m_pdelBuf)[index][3];
    QString tableval12 = (*m_pdelBuf)[index][4];
    QString tableName2 = (*m_pdelBuf)[index][5];
    QString tableKey21 = (*m_pdelBuf)[index][6];
    QString tableKey22 = (*m_pdelBuf)[index][7];

    QString str_1 = QString(
        "delete from %1 "
        "where %2 = '%3' and %4 = %5"
    ).arg(tableName1)\
        .arg(tableKey11)\
        .arg(tableval11)\
        .arg(tableKey12)\
        .arg(tableval12); 

    QString str_2 = QString(
        "update %1 "
        "set %2 = %3+1 "
        "where %4 = %5"
    ).arg(tableName2)\
        .arg(tableKey22)\
        .arg(tableKey22)\
        .arg(tableKey21)\
        .arg(tableval12);

    QSqlDatabase::database().transaction();     // 开启一个事务
    bool delete_flag = m_pqueryOrder->exec(str_1);
    bool update_flag = m_pqueryOrder->exec(str_2);
    if (!update_flag && !update_flag) {
        QMessageBox::warning(this, QString("error!"), QString("Can't delete Order!"), QMessageBox::Ok);
        if (update_flag || delete_flag) {
            QSqlDatabase::database().rollback();
        }
        return;
    }
    QSqlDatabase::database().commit();          // 提交
    QMessageBox::warning(this, QString("Sucess!"), QString("Delete sucessful!"), QMessageBox::Ok);
    AddOrderToPeekOrderWindow();
}

// 信号槽
void QtWidgetsApplication::PeekOrderWindowConnectInit()
{
    connect(m_pPeekOrderWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnPeekOrderWindowBackBtn);
    connect(m_pPeekOrderWindow->ui.btn_delete, &QPushButton::clicked, this, &QtWidgetsApplication::OnPeekOrderWindowDeleteBtn);
}

// 将订单添加到表格控件
void QtWidgetsApplication::AddOrderToPeekOrderWindow()
{
    std::vector<QString> elem_pool;             // 订单内容
    if (m_pdelBuf != nullptr) {
        delete m_pdelBuf;
    }
    m_pdelBuf = new std::vector<std::vector<QString>>();
    int nums = 0;                               // 元素编号           

/*------查询订单信息--------*/
    QString str_1 = QString(
        "select car.type, car.price, car.carID, customercar.date, customercar.time, customercar.customer_1, customercar.car "
        "from customercar inner join car "
        "on customercar.car = car.noCar and customercar.customer_1 = '%1'").arg(user_id);
    if (!m_pqueryOrder->exec(str_1)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find Order infomation!"), QMessageBox::Ok);
    }
    // 取出数据库中找到的元素
    while (m_pqueryOrder->next()) {
        QString buff;
        buff += QString::fromUtf8("车类型：");
        buff += m_pqueryOrder->value(0).toString();
        buff += QString::fromUtf8("，价格：");
        buff += m_pqueryOrder->value(1).toString();
        buff += QString::fromUtf8("，联系电话：");
        buff += m_pqueryOrder->value(2).toString();
        buff += QString::fromUtf8("，订单创建日期：");
        buff += m_pqueryOrder->value(3).toString();
        buff += QString::fromUtf8("，订单创建时间：");
        buff += m_pqueryOrder->value(4).toString();
        elem_pool.push_back(buff);
        std::vector<QString> delB;
        delB.push_back(QString("customercar"));                 // 表
        delB.push_back(QString("customercar.customer_1"));      // 属性1
        delB.push_back(QString("customercar.car"));             // 属性2
        delB.push_back(m_pqueryOrder->value(5).toString());     // 键1
        delB.push_back(m_pqueryOrder->value(6).toString());     // 键2
        delB.push_back(QString("car"));                         // 表
        delB.push_back(QString("noCar"));                   // 属性1
        delB.push_back(QString("leftCars"));                // 属性2
        m_pdelBuf->push_back(delB);
    }

    QString str_2 = QString(
        "select flight.formCity, flight.ariveCity, flight.price, flight.flyDate,flight.ariveDate,customerflight.date, customerflight.time,customerflight.customer_2,customerflight.flight "
        "from customerflight inner join flight "
        "on customerflight.flight = flight.noFlight and customerflight.customer_2 = '%1'").arg(user_id);
    if (!m_pqueryOrder->exec(str_2)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find Order infomation!"), QMessageBox::Ok);
    }
    // 取出数据库中找到的元素
    while (m_pqueryOrder->next()) {
        QString buff;
        buff += QString::fromUtf8("起飞城市：");
        buff += m_pqueryOrder->value(0).toString();
        buff += QString::fromUtf8("，降落城市：");
        buff += m_pqueryOrder->value(1).toString();
        buff += QString::fromUtf8("，价格：");
        buff += m_pqueryOrder->value(2).toString();
        buff += QString::fromUtf8("，起飞日期：");
        buff += m_pqueryOrder->value(3).toString();
        buff += QString::fromUtf8("，降落日期：");
        buff += m_pqueryOrder->value(4).toString();
        buff += QString::fromUtf8("，订单创建日期：");
        buff += m_pqueryOrder->value(5).toString();
        buff += QString::fromUtf8("，订单创建时间：");
        buff += m_pqueryOrder->value(6).toString();
        elem_pool.push_back(buff);
        std::vector<QString> delB;
        delB.push_back(QString("customerflight"));              // 表
        delB.push_back(QString("customerflight.customer_2"));   // 属性1
        delB.push_back(QString("customerflight.flight"));       // 属性2
        delB.push_back(m_pqueryOrder->value(7).toString());     // 键1
        delB.push_back(m_pqueryOrder->value(8).toString());     // 键2
        delB.push_back(QString("flight"));                      // 表
        delB.push_back(QString("noFlight"));             // 属性1
        delB.push_back(QString("leftSeats"));            // 属性2
        m_pdelBuf->push_back(delB);
    }

    QString str_3 = QString(
        "select hotel.name, hotel.price, hotel.location, customerhotel.date, customerhotel.time,customerhotel.customer_3,customerhotel.hotel "
        "from customerhotel inner join hotel "
        "on customerhotel.hotel = hotel.noHotel and customerhotel.customer_3 = '%1'").arg(user_id);
    if (!m_pqueryOrder->exec(str_3)) {
        QMessageBox::warning(this, QString("error!"), QString("Can't find Order infomation!"), QMessageBox::Ok);
    }
    // 取出数据库中找到的元素
    while (m_pqueryOrder->next()) {
        QString buff;
        buff += QString::fromUtf8("宾馆：");
        buff += m_pqueryOrder->value(0).toString();
        buff += QString::fromUtf8("，价格：");
        buff += m_pqueryOrder->value(1).toString();
        buff += QString::fromUtf8("，地址：");
        buff += m_pqueryOrder->value(2).toString();
        buff += QString::fromUtf8("，订单创建日期：");
        buff += m_pqueryOrder->value(3).toString();
        buff += QString::fromUtf8("，订单创建时间：");
        buff += m_pqueryOrder->value(4).toString();
        elem_pool.push_back(buff);
        std::vector<QString> delB;
        delB.push_back(QString("customerhotel"));               // 表
        delB.push_back(QString("customerhotel.customer_3"));    // 属性1
        delB.push_back(QString("customerhotel.hotel"));         // 属性2
        delB.push_back(m_pqueryOrder->value(5).toString());     // 键1
        delB.push_back(m_pqueryOrder->value(6).toString());     // 键2
        delB.push_back(QString("hotel"));                       // 表
        delB.push_back(QString("noHotel"));               // 属性1
        delB.push_back(QString("leftRooms"));             // 属性2
        m_pdelBuf->push_back(delB);
    }


/*------设置订单信息--------*/
    QTableWidget* tmp = m_pPeekOrderWindow->ui.tableWidget;
    m_pPeekOrderWindow->ui.label_4->setText(user_id);
    tmp->setRowCount(elem_pool.size());                         // 设置表格的行数
    tmp->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 设置表格不可编辑


    int row = 0;    // 行
    while (row < elem_pool.size()) {        // 将查到的每条信息放入表格中
        tmp->setItem(row, 0, new QTableWidgetItem(QString("%1").arg(row +1)));
        tmp->setItem(row, 1, new QTableWidgetItem(elem_pool[row]));
        row++;
    }
    // 设置删除选择框
    m_pPeekOrderWindow->ui.comboBox->clear();
    for (int i = 0; i < elem_pool.size(); ++i) {
        m_pPeekOrderWindow->ui.comboBox->addItem(QString("%1").arg(i+1));
    }

}


/*--------------------------------------------------------------查询路线窗口---------------------------------------------------*/
// 退出按钮响应函数
void QtWidgetsApplication::OnPeekRoadWindowBackBtn()
{
    // 关闭查询路线窗口
    m_pPeekRoadWindow->close();

    // 清除查询路线窗口
    delete m_pPeekRoadWindow;
    m_pPeekRoadWindow = nullptr;

    // 清除过时的查询路线信息
    delete m_pqueryRoad;
    m_pqueryRoad = nullptr;

    // 显示菜单窗口
    m_pMenuWindow->show();
}

// 信号槽
void QtWidgetsApplication::PeekRoadWindowConnectInit()
{
    connect(m_pPeekRoadWindow->ui.btn_back, &QPushButton::clicked, this, &QtWidgetsApplication::OnPeekRoadWindowBackBtn);
}

// 将订单添加到表格控件
void QtWidgetsApplication::AddRoadToPeekRoadWindow()
{
    /*------查询订单信息--------*/
    QString str_1 = QString(
        "select formCity,ariveCity,flyDate,ariveDate "
        "from flight "
        "where noFlight in (select customerflight.flight "
                           "from customerflight "
                           "where customerflight.customer_2 = '%1')").arg(user_id);
    if (!m_pqueryRoad->exec(str_1)) {
        QMessageBox::warning(this, QString("error!"), QString("路线查询失败"), QMessageBox::Ok);
    }
    // 取出数据库中找到的元素
    std::vector<std::vector<QString>> elem_pool;
    while (m_pqueryRoad->next()) {
        std::vector<QString> buff;
        for (int i = 0; i < 4; i++) {
            buff.push_back(m_pqueryRoad->value(i).toString());
        }
        elem_pool.push_back(buff);
    }

    QTableWidget* tmp = m_pPeekRoadWindow->ui.tableWidget;
    tmp->setRowCount(elem_pool.size());                         // 设置表格的行数
    tmp->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 设置表格不可编辑

    int col = 0;    // 列
    int row = 0;    // 行
    while (row < elem_pool.size()) {        // 将查到的每条信息放入表格中
        col = 0;
        while (col < 4) {
            tmp->setItem(row, col, new QTableWidgetItem(elem_pool[row][col]));
            col++;
        }
        row++;
    }
}